package com.meihuayishu.backend.controller;

import com.meihuayishu.backend.common.ApiResponse;
import com.meihuayishu.backend.dto.DivinationFeedbackDTO;
import com.meihuayishu.backend.entity.DivinationFeedback;
import com.meihuayishu.backend.entity.User;
import com.meihuayishu.backend.repository.UserRepository;
import com.meihuayishu.backend.service.FeedbackService;
import com.meihuayishu.backend.util.DivinationAccuracyAnalyzer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/divination/feedback")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "占卜反馈接口", description = "用户对占卜结果的反馈管理和准确性分析")
public class FeedbackController {
    
    private final FeedbackService feedbackService;
    private final UserRepository userRepository;
    private final DivinationAccuracyAnalyzer accuracyAnalyzer;
    
    @PostMapping
    @Operation(summary = "提交反馈", description = "用户提交对占卜结果的反馈")
    public ApiResponse<DivinationFeedbackDTO> submitFeedback(@RequestBody DivinationFeedbackDTO feedbackDTO) {
        try {
            // 验证用户存在
            User user = userRepository.findById(feedbackDTO.getUserId())
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
            
            // 创建反馈实体
            DivinationFeedback feedback = new DivinationFeedback();
            feedback.setUserId(feedbackDTO.getUserId());
            feedback.setDivinationType(feedbackDTO.getDivinationType());
            feedback.setOriginalHexagram(feedbackDTO.getOriginalHexagram());
            feedback.setChangedHexagram(feedbackDTO.getChangedHexagram());
            feedback.setIsAccurate(feedbackDTO.getIsAccurate());
            feedback.setFeedbackComment(feedbackDTO.getFeedbackComment());
            feedback.setUserCity(user.getCurrentCity());
            feedback.setUserMood(user.getMoodStatus());
            
            // 保存反馈
            DivinationFeedback savedFeedback = feedbackService.saveFeedback(feedback);
            
            // 转换为DTO返回
            DivinationFeedbackDTO savedDTO = new DivinationFeedbackDTO();
            savedDTO.setId(savedFeedback.getId());
            savedDTO.setUserId(savedFeedback.getUserId());
            savedDTO.setDivinationType(savedFeedback.getDivinationType());
            savedDTO.setOriginalHexagram(savedFeedback.getOriginalHexagram());
            savedDTO.setChangedHexagram(savedFeedback.getChangedHexagram());
            savedDTO.setIsAccurate(savedFeedback.getIsAccurate());
            savedDTO.setFeedbackComment(savedFeedback.getFeedbackComment());
            savedDTO.setUserCity(savedFeedback.getUserCity());
            savedDTO.setUserMood(savedFeedback.getUserMood());
            savedDTO.setCreatedAt(savedFeedback.getCreatedAt());
            
            return ApiResponse.success(savedDTO);
        } catch (Exception e) {
            log.error("提交反馈失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户反馈历史", description = "获取指定用户的反馈历史")
    public ApiResponse<List<DivinationFeedbackDTO>> getUserFeedback(@PathVariable Long userId) {
        try {
            List<DivinationFeedbackDTO> feedbacks = feedbackService.getFeedbackByUserId(userId);
            return ApiResponse.success(feedbacks);
        } catch (Exception e) {
            log.error("获取用户反馈历史失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    @GetMapping("/stats/hexagram")
    @Operation(summary = "获取卦象准确率统计", description = "获取各卦象的准确率统计")
    public ApiResponse<Map<String, Double>> getHexagramAccuracyRates() {
        try {
            Map<String, Double> accuracyRates = feedbackService.getHexagramAccuracyRates();
            return ApiResponse.success(accuracyRates);
        } catch (Exception e) {
            log.error("获取卦象准确率统计失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    @GetMapping("/stats/city")
    @Operation(summary = "获取城市准确率统计", description = "获取各城市的准确率统计")
    public ApiResponse<Map<String, Double>> getCityAccuracyRates() {
        try {
            Map<String, Double> accuracyRates = feedbackService.getCityAccuracyRates();
            return ApiResponse.success(accuracyRates);
        } catch (Exception e) {
            log.error("获取城市准确率统计失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    @GetMapping("/stats/mood")
    @Operation(summary = "获取心情准确率统计", description = "获取各心情状态的准确率统计")
    public ApiResponse<Map<String, Double>> getMoodAccuracyRates() {
        try {
            Map<String, Double> accuracyRates = feedbackService.getMoodAccuracyRates();
            return ApiResponse.success(accuracyRates);
        } catch (Exception e) {
            log.error("获取心情准确率统计失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    @PostMapping("/analyze")
    @Operation(summary = "手动触发反馈分析", description = "手动触发反馈数据分析和权重更新")
    public ApiResponse<String> triggerAnalysis() {
        try {
            feedbackService.analyzeAndUpdateWeights();
            return ApiResponse.success("反馈数据分析和权重更新已完成");
        } catch (Exception e) {
            log.error("触发反馈分析失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    @GetMapping("/analysis/city-hexagram")
    @Operation(summary = "获取城市卦象准确率分析", description = "分析不同城市对不同卦象的准确率")
    public ApiResponse<Map<String, Map<String, Double>>> getCityHexagramAccuracyAnalysis() {
        try {
            Map<String, Map<String, Double>> analysis = accuracyAnalyzer.analyzeCityHexagramAccuracy();
            return ApiResponse.success(analysis);
        } catch (Exception e) {
            log.error("获取城市卦象准确率分析失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    @GetMapping("/analysis/mood-hexagram")
    @Operation(summary = "获取心情卦象准确率分析", description = "分析不同心情对不同卦象的准确率")
    public ApiResponse<Map<String, Map<String, Double>>> getMoodHexagramAccuracyAnalysis() {
        try {
            Map<String, Map<String, Double>> analysis = accuracyAnalyzer.analyzeMoodHexagramAccuracy();
            return ApiResponse.success(analysis);
        } catch (Exception e) {
            log.error("获取心情卦象准确率分析失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    @PostMapping("/analysis/clear-cache")
    @Operation(summary = "清除分析缓存", description = "清除占卜准确性分析缓存")
    public ApiResponse<String> clearAnalysisCache() {
        try {
            accuracyAnalyzer.clearAnalysisCache();
            return ApiResponse.success("分析缓存已清除");
        } catch (Exception e) {
            log.error("清除分析缓存失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
}
